package com.jse.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.jse.json.JsonObject;

public class Location {
	
	
	/**
	 * 获取最短的距离
	 * @param list map -> lat lon (会新增sort)
	 * @param lat 比较点x
	 * @param lon 比较点y
	 * @return
	 */
	public static List<JsonObject> shortLocation(List<JsonObject> list,Double lat,Double lon) {
        List<JsonObject> ilist = new ArrayList<JsonObject>();
        for (int i = 0; i < list.size(); i++) {
        	JsonObject m=list.get(i);
        	Double z = getShortLocal(m.getDouble("lat"),m.getDouble("lon"), lat, lon); 
        	m.put("sort", z);
        	//获取最短距离后把经纬度和距离存放到对象中
        	ilist.add(m);
		}
        return shortLocation(ilist);
    }
	public static List<JsonObject> shortLocation(List<JsonObject> list,Double lat,Double lon,String sort) {
        List<JsonObject> ilist = new ArrayList<JsonObject>();
        for (int i = 0; i < list.size(); i++) {
        	JsonObject m=list.get(i);
        	Double z = getShortLocal(m.getDouble("lat"),m.getDouble("lon"), lat, lon); 
        	m.put(sort, z);
        	//获取最短距离后把经纬度和距离存放到对象中
        	ilist.add(m);
		}
        return shortLocation(ilist);
    }

	/**
	 * 获取最短的距离
	 * 
	 * @param lat
	 * @param lon
	 * @param initlat
	 * @param initlon
	 * @return
	 */
	public static Double getShortLocal(Double lat, Double lon, Double initlat, Double initlon) {
		Double x = (initlat - lat) * (initlat - lat);
		Double y = (initlon - lon) * (initlon - lon);
		Double z = Math.sqrt(x + y);
		return z;
	}

	/**
	 * 排序
	 * @list 可用于数据库中的查询 字段
	 * @sort 排序字段
	 * @return
	 */
	public static List<JsonObject> shortLocation(List<JsonObject> list) {
		return shortLocation(list, "sort");
	}
	public static List<JsonObject> shortLocation(List<JsonObject> list,String sort) {
		Collections.sort(list, (arg0,arg1)->{
				Double double1 = arg0.getDouble(sort);
				Double double2 = arg1.getDouble(sort);
				if (double1 > double2) {
					return 1;
				} else if (double1 == double2) {
					return 0;
				} else {
					return -1;
				}
		});
		return list;
	}

}